package com.yunxin.admin.system.infra.framework.security.userdetails;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yunxin.admin.system.application.UserQueryService;
import com.yunxin.admin.system.infra.common.constant.SystemConstants;
import com.yunxin.admin.system.infra.framework.security.exception.MobileNotFoundException;
import com.yunxin.admin.system.infra.persistence.entity.query.result.UserAuthInfoResult;
import com.yunxin.admin.system.infra.persistence.mapper.SysUserMerchantMapper;
//import com.yunxin.core.application.service.UserTeamShipService;
//import com.yunxin.core.domain.model.team.UserTeamShip;
import com.yunxin.core.admin.domain.AdminUserTeamShip;
import com.yunxin.core.admin.service.AdminUserTeamShipService;
import lombok.RequiredArgsConstructor;
import org.mapstruct.ap.internal.model.assignment.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * 用户认证信息实现类
 *
 * @author zero°
 * @since 2023-05-22
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsExternalService {

    private final UserQueryService userQueryService;

    @Autowired
    private SysUserMerchantMapper sysUserMerchantMapper;

    @Autowired
    private AdminUserTeamShipService userTeamShipService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAuthInfoResult userAuthInfoResult = userQueryService.getUserAuthInfo(username, SystemConstants.LOGIN_TYPE_USERNAME);
        if (userAuthInfoResult == null) {
            throw new UsernameNotFoundException("用户不存在,username=" +username);
        }
        List<Long> longs = sysUserMerchantMapper.listMerchantIdsByUserId(userAuthInfoResult.getUserId());
        if (!ObjectUtils.isEmpty(longs)){
            userAuthInfoResult.setMerchantId(longs.get(0));
        }
        LambdaQueryWrapper<AdminUserTeamShip> teamShipLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teamShipLambdaQueryWrapper.eq(AdminUserTeamShip::getUserMerchantId, userAuthInfoResult.getUserId())
                .orderByDesc(AdminUserTeamShip::getLastLoginTime).last("limit 1");
        AdminUserTeamShip userTeamShip = userTeamShipService.getOne(teamShipLambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(userTeamShip)){
            userAuthInfoResult.setTeamId(userTeamShip.getTeamId().intValue());
            LambdaUpdateWrapper<AdminUserTeamShip> updateWrapper=new LambdaUpdateWrapper();
            updateWrapper.eq(AdminUserTeamShip::getTeamId,userTeamShip.getTeamId())
                    .eq(AdminUserTeamShip::getUserMerchantId,userTeamShip.getUserMerchantId())
                    .set(AdminUserTeamShip::getLastLoginTime,new Date());
            userTeamShipService.update(updateWrapper);
        }
        return new SysUserDetails(userAuthInfoResult);
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) throws MobileNotFoundException {
        UserAuthInfoResult userAuthInfoResult = userQueryService.getUserAuthInfo(mobile, SystemConstants.LOGIN_TYPE_MOBILE);
        if (userAuthInfoResult == null) {
            throw new MobileNotFoundException("用户不存在,mobile=" +mobile);
        }
        List<Long> longs = sysUserMerchantMapper.listMerchantIdsByUserId(userAuthInfoResult.getUserId());
        if (!ObjectUtils.isEmpty(longs)){
            userAuthInfoResult.setMerchantId(longs.get(0));
        }
        LambdaQueryWrapper<AdminUserTeamShip> teamShipLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teamShipLambdaQueryWrapper.eq(AdminUserTeamShip::getUserMerchantId, userAuthInfoResult.getUserId())
                .orderByDesc(AdminUserTeamShip::getLastLoginTime).last("limit 1");
        AdminUserTeamShip userTeamShip = userTeamShipService.getOne(teamShipLambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(userTeamShip)){
            userAuthInfoResult.setTeamId(userTeamShip.getTeamId().intValue());
            LambdaUpdateWrapper<AdminUserTeamShip> updateWrapper=new LambdaUpdateWrapper();
            updateWrapper.eq(AdminUserTeamShip::getTeamId,userTeamShip.getTeamId())
                    .eq(AdminUserTeamShip::getUserMerchantId,userTeamShip.getUserMerchantId())
                    .set(AdminUserTeamShip::getLastLoginTime,new Date());
            userTeamShipService.update(updateWrapper);
        }
        return new SysUserDetails(userAuthInfoResult);
    }
}
